import React from 'react'
import dispatcher from 'lib/dispatcher'
import cx from 'classnames'
import moment from 'moment'
import DatePicker from 'lib/components/datepicker.jsx'
import _ from 'underscore'
import $ from 'jquery'

import { defaultApi } from '../apis/core-util';

class DatePicker2 extends DatePicker {
  onForward(key){
    var next = moment(this.state.currentShow).add(1, 'month');
    if(!next.isAfter(this.props.maxDate)) {
      this.setState(this.stateFromDate(next.valueOf(), false), this._onChange);
    } else {
      this.setState(this.stateFromDate(this.props.maxDate.valueOf(), false), this._onChange);
    }
  }

  onBackward(key){
    var previous = moment(this.state.currentShow).subtract(1, 'month');
    if(!previous.isBefore(this.props.minDate)) {
      this.setState(this.stateFromDate(previous.valueOf(), false), this._onChange);
    } else {
      this.setState(this.stateFromDate(this.props.minDate, false), this._onChange)
    }
  }

  isDisabled(timestamp,month,currentMonth){
    return !(timestamp >= this.props.minDate && timestamp <= this.props.maxDate) || month !== undefined && month !== currentMonth
  }

  selectDay(date, event) {
    this.setState(this.stateFromDate(date),this._onChange)
  }

  render() {
    return (
      <div className="calendar-date">
        <table className="table-condensed">
          <thead>
            <tr>
              <th>
                <i className="iconfont arrow" style={{color:'#555'}} onClick={this.state.allowBackward?this.onBackward:null}>
                  &#xe63e;
                </i>
              </th>
              <th colSpan="5">
                {this.state.year}年 {this.state.month+1}月
              </th>
              <th>
                <i className="iconfont arrow" style={{color:'#555'}} onClick={this.state.allowForward?this.onForward:null}>
                  &#xe63f;
                </i>
              </th>
            </tr>
            <tr>
              <th>日</th>
              <th>一</th>
              <th>二</th>
              <th>三</th>
              <th>四</th>
              <th>五</th>
              <th>六</th>
            </tr>
          </thead>
          <tbody>
            {
              this.state.matrix.map(function(week,n){
                return (
                  <tr key={n}>
                    {
                      week.map(function(dayObj){
                        if(this.isDisabled(dayObj.value,dayObj.month,this.state.month)){
                          return (
                            <td className="disabled" key={dayObj.date}>
                              {dayObj.label}
                            </td>
                          )
                        }else{
                          return (
                            <td onClick={this.selectDay.bind(this,dayObj.value)} className={cx({
                                active:dayObj.date === this.state.date && dayObj.month === this.state.month
                              })} key={dayObj.date}>
                              {dayObj.label}
                            </td>
                          )
                        }
                      },this)
                    }
                  </tr>
                )
              },this)
            }
          </tbody>
        </table>
      </div>
    )
  }
}

export default class DateComparerPickerEnhanced extends React.Component {
  constructor(props, context){
    super(props, context);

    this.state = _.extend({}, this.getStateFromProps(props), {
      isOpen: false,
      minDate: moment().startOf('day').subtract(1, 'years').valueOf(),
      maxDate: moment().startOf('day').valueOf() - props.spanTime
    });

    this.toggle = this.toggle.bind(this);
    this.dayChanged = this.dayChanged.bind(this);
    this.applyHandler = this.applyHandler.bind(this);
    this.globalCloseDisplay = this.globalCloseDisplay.bind(this);
    this.getDisplayText = this.getDisplayText.bind(this);

    this.partitionApi = defaultApi({
      __url: `sd/${ BlueWare.appId }/api/partitions/list`
    });
  } // constructor

  getStateFromProps(props) {
    return {
      endTime: props.endTime
                 ? moment(props.endTime).startOf('day').valueOf()
                 : moment(props.beginTime + props.spanTime).startOf('day').valueOf()
    };
  } // getStateFromProps

  getDisplayText(props = this.props) {
    return moment(this.state.endTime - this.props.spanTime).format('YYYY-MM-DD') + ' ~ ' + moment(this.state.endTime).format('YYYY-MM-DD');
  } // getDisplayText

  toggle(event) {
    this.setState({
      isOpen: !this.state.isOpen
    });
  } // toggle

  dayChanged(date) {
    this.setState({
      endTime: date + this.props.spanTime
    });
  } // dayChanged

  applyHandler() {
    this.setState({
      isOpen: false
    }, () => this.props.onCompleted({
      startTime: this.startTime,
      spanTime: this.props.spanTime,
      endTime: this.state.endTime
    }));
  } // applyHandler

  globalCloseDisplay(e) {
    if (this.state.isOpen && !$.contains(this.refs.root, e.target)) {
      this.setState({
        isOpen: false
      });
    }
  } // globalCloseDisplay

  componentDidMount() {
    $(document.body).on('click', this.globalCloseDisplay);
  } // componentDidMount

  componentWillReceiveProps(nextProps) {
    this.setState(this.getStateFromProps(nextProps));
  } // componentWillReceiveProps

  componentWillUnmount() {
    $(document.body).off('click', this.globalCloseDisplay);
  } // componentWillUnmount

  renderBody() {
    let endTime = moment(this.state.endTime).format('YYYY-MM-DD');
    this.startTime = this.state.endTime - this.props.spanTime;

    return (
      <div className="mi-timepicker-dropdown-main" style={{ width: 286 }}>
        <div className="timepicker-main" style={{
          width: 270,
          margin: '0 auto',
          paddingTop: '0px'
        }}>
          <div style={{ 'marginBottom': '10px' }}>
            <span style={{ color: '#999999' }}>选择起始日</span>
            <span className="float-right" style={{ color:'#c2c2c2' }}>
              ({ moment.duration(this.props.spanTime).asDays() + 1 } 天)
            </span>
          </div>
          <div className="timepicker-diy">
            <DatePicker2
              key={ Date.now() }
              minDate={ this.state.minDate }
              maxDate={ this.state.maxDate }
              defaultValue={ this.startTime }
              onAfterChange={ this.dayChanged } />
          </div>
        </div>
        <div className="timepicker-footer">
          <span style={{
            float: 'left',
            marginLeft: '0px',
            lineHeight: '34px',
            color: '#888888'
          }}>
            对比 { moment(this.startTime).format('YYYY-MM-DD') } 至 { endTime }
          </span>
          <button onClick={ this.applyHandler } className="btn-green" type="button">确定</button>
        </div>
      </div>
    )
  }

  render() {
    let currentStyle = _.extend({ display: 'inline-block' }, this.props.style);
    return (
      <div className="dropdown time-slider" style={ currentStyle } ref="root">
        <strong onClick={ this.toggle }>
          <i className="iconfont icon-clock"></i>
            { this.getDisplayText() }
          <i className="iconfont icon-btn-arrow">&#xe619;</i>
        </strong>
        { this.state.isOpen ? this.renderBody() : null }
      </div>
    );
  } // render
} // renderBody

DateComparerPickerEnhanced.defaultProps = {
  spanTime: moment.duration(1, 'days').valueOf(),
  beginTime: null,
  endTime: null,
  style: {},
  onCompleted: item => {}
}
